-- Initialize Ace2
KragHonor2 = AceLibrary("AceAddon-2.0"):new("AceEvent-2.0", "AceDB-2.0", "AceConsole-2.0");

function KragHonor2:OnInitialize() -- {{{
	-- Register the Internal DB
	self:RegisterDB("KragHonor2DB");

	-- Register the bare-bone defaults
	self:RegisterDefaults( "profile", {
		goal = 0,
		display = true,
		zone = GetRealZoneText(),
		subZone = GetSubZoneText(),
		x = 0,
		y = 0,
		diff = 0,
		cumulativeHonor = 0,
		honorPercent = 0,
		color = { r = 0.41, g = 0.70, b = 0.94, },
		marks = { name = "", type = "", num = 0 },
		armorSet = { },
		weaponSet = { },
	} );

	-- Register the slash commands
	local slashOptions = {
		type = 'group',
		args = {
			goal = {
				type = 'range',
				name = 'goal',
				desc = 'Your current goal for honor currency.',
				min = 0,
				max = 75000,
				step = 1,
				error = "%s is not a valid goal.",
				message = "Your %s has been set to %s.",
				current = "Your current %s is %s.",
				get = 'getGoal',
				set = 'setGoal',
			},
			display = {
				type = 'toggle',
				name = 'display',
				desc = 'Display honor updates after each battleground?',
				get = 'getDisplay',
				set = 'setDisplay',
				hidden = true,
			},
			run = {
				type = 'execute',
				name = 'run',
				desc = 'Compute the honor you currently need.',
				func = function() self:computeHonor( true ) end,
			},
			zoneCheck = {
				type = 'execute',
				name = 'zoneCheck',
				desc = 'Check the stored zone information...',
				func = function() self:Print( "ZONE: " .. self.db.profile.zone .. " SUBZONE:" .. self.db.profile.subZone ); end,
				hidden = true,
			},
			x = {
				type = 'text',
				name = 'x',
				desc = "X-Coordinate for the HonorBar",
				usage = '<Uh>',
				get = 'getX',
				set = 'setX',
			},
			y = {
				type = 'text',
				name = 'y',
				desc = 'Y-Coordinate for the HonorBar',
				usage = '<Uhm>',
				get = 'getY',
				set = 'setY',
			},
			show = {
				type = 'execute',
				name = 'show',
				desc = 'Show the HonorBar!',
				func = function() self:CreateBar(); end,
			},
			update = {
				type = 'execute',
				name = 'update',
				desc = 'Update the HonorBar',
				func = function() self:Print("DIFF: "..self.db.profile.diff); self:UpdateHonorBar(); end,
				hidden = true,
			},
		},
	};

	self:LoadOptions();
	--self.dewdrop:Open( UIParent, 'children', function() self.dewdrop:FeedAceOptionsTable( self.opts ); end, 'cursorX', true, 'cursorY', true );

	self:RegisterChatCommand ( { "/kh2", "/kraghonor2" }, slashOptions );
end
-- }}}
function KragHonor2:OnEnable() -- {{{
	-- Register Events
	self:RegisterEvent("CHAT_MSG_COMBAT_HONOR_GAIN");
	--self:RegisterEvent("PLAYER_PVP_KILLS_CHANGED");

	-- Set the UI
	if not KragHonor2Bar then
		self:CreateBar();
		--self:loadArmorSets();
		--self:loadWeaponSets();
	end
end
--}}}
function KragHonor2:CHAT_MSG_COMBAT_HONOR_GAIN( arg ) -- {{{
	self:UpdateHonorBar( true );
end
-- }}}
function KragHonor2:wasZoneBattleground ( zone ) -- {{{
	if zone == "Alterac Valley" or zone == "Arathi Basin" or zone == "Warsong Gulch" then
		return true;
	else
		return false;
	end
end
-- }}}
function KragHonor2:getX() -- {{{
	return self.db.profile.x;
end
-- }}}
function KragHonor2:setX( newX ) -- {{{
	self.db.profile.x = newX;
end
-- }}}
function KragHonor2:getY() -- {{{
	return self.db.profile.y;
end
-- }}}
function KragHonor2:setY( newY ) -- {{{
	self.db.profile.y = newY;
end
-- }}}
function KragHonor2:getDisplay() -- {{{
	return self.db.profile.display;
end
-- }}}
function KragHonor2:setDisplay( newDisplay ) -- {{{
	self.db.profile.display = newDisplay;
end
-- }}}
function KragHonor2:getGoal() -- {{{
	return self.db.profile.goal;
end
-- }}}
function KragHonor2:setGoal( newGoal, newMarks ) -- {{{
	self.db.profile.goal = newGoal;

	if newMarks then
		-- Store the needed marks
		self.db.profile.marks = newMarks;

		-- Set the text in the UI
		if KragHonor2Bar then
			KragHonor2Bar.goalName:SetText(newMarks.name);
		end
	end

	-- Since the goal was changed, we need to update the bar and recalc
	self:computeHonor( false );
end
-- }}}
function KragHonor2:computeHonor ( outputToUser ) -- {{{
	local todayKills, todayHonor = GetPVPSessionStats();
	local honorCurrency = GetHonorCurrency();

	self.db.profile.cumulativeHonor = honorCurrency + todayHonor;
	self.db.profile.diff = self.db.profile.goal - self.db.profile.cumulativeHonor;

	local diff = self.db.profile.diff;

	if diff < 0 then
		diff = math.abs( diff );

		if outputToUser then
			self:print( "you have met your goal.  you are currently |cff00ff00" .. diff .. "|r over your goal of " .. self.db.profile.goal .. "." );
		end
		self.db.profile.honorPercent = 100;
	else
		self.db.profile.honorPercent = math.round ( ( self.db.profile.cumulativeHonor / self.db.profile.goal ) * 100, 2 );
		local diffColor = self:colorFormatNumber( self.db.profile.honorPercent );

		if outputToUser then
			self:Print( "You need |cFFFF0000" .. diff .. "|r honor to reach your goal of " .. self.db.profile.goal .. " (" .. diffColor .. "%)." );
		end
	end

	if KragHonor2Bar then
		self:UpdateHonorBar( false );
	end
end
-- }}}
function KragHonor2:colorFormatNumber ( inValue ) -- {{{
	local tmp = "";
	if inValue == 100 then
		tmp = "00FF00";
	elseif inValue >= 80 and inValue <= 99 then
		tmp = "00AA00";
	elseif inValue >= 50 and inValue <= 79 then
		tmp = "E5D41B";
	elseif inValue >= 30 and inValue <= 49 then
		tmp = "E59D12";
	elseif inValue >= 0 and inValue <= 29 then
		tmp = "FF0000";
	else
		tmp = "A6A6A6";
	end

	return "|cFF" .. tmp .. inValue .. "|r";
end
-- }}}
function KragHonor2:SendOutput ( msg, target, medium ) -- {{{
	-- Make it lowercase, incase someone can't type!
	if not medium then
		medium = "";
	end

	medium = string.lower(medium);

	if ( medium == "console" ) then
		DEFAULT_CHAT_FRAME:AddMessage ( KragHonor_Prefix .. " " .. msg );
	elseif ( medium == "whisper" ) then
		SendChatMessage ( msg, "WHISPER", nil, target );
	elseif ( medium == "guild" ) then
		SendChatMessage ( msg, "GUILD", nil);
	elseif ( medium == "officer" ) then
		SendChatMessage ( msg, "OFFICER", nil);
	elseif ( medium == "channel" ) then
		local channelIndex = GetChannelName(target);
		SendChatMessage ( msg, "CHANNEL", nil, channelIndex );
	elseif ( medium == "party" ) then
		SendChatMessage ( msg, "PARTY", nil );
	elseif ( medium == "say" ) then
		SendChatMessage ( msg, "SAY", nil );
	elseif ( medium == "yell" ) then
		SendChatMessage ( msg, "YELL", nil );
	elseif ( medium == "raid" ) then
		SendChatMessage ( msg, "RAID", nil );
	elseif ( medium == "raidwarning" ) then
		SendChatMessage ( msg, "RAID_WARNING", nil );
	elseif ( medium == "battleground" ) then
		SendChatMessage ( msg, "BATTLEGROUND", nil );
	end
end
-- }}}
function math.round( num, idp ) -- {{{
	return tonumber( string.format("%."..idp.."f", num ) )
end
-- }}}
function KragHonor2:getItemLink ( item ) -- {{{
	local itemName, itemLink, itemRarity, itemLevel, itemMinimumLevel, itemType, itemSubType, itemStackSize, itemEquipLocation, itemTexture = GetItemInfo( item );

	if (not itemLink) or (itemLink == nil) or (itemLink == "") then
		return item;
	else
		return itemLink;
	end
end --}}}
function KragHonor2:formatNumber ( n ) -- {{{
	local tmp = n;
	local out = "";
	local a = "";

	while string.len(tmp) >= 3 do
		a = string.sub(n, -3);
		out = out .. "," .. a;
		tmp = string.gsub( tmp, a.."$", "" );
	end

	if string.len(tmp) > 0 then
		out = tmp .. out;
	else
		-- Clean the commas
		out = string.gsub(out, "^,", "");
	end

	return out;
end
-- }}}
